import Taro, { setStorageSync, getStorageSync, removeStorageSync } from "@tarojs/taro"
import { judgeType, objToString } from './utils'

interface RequestProps {
  url?: string,
  params?: object,
  method?: keyof Method,
  header?: object,
}

const tools = {
  /**
   * 网络请求
   */
  request,
  /**
   * 开启页面 loading
   */
  showLoading,
  /**
   * 页面提示
   */
  showToast,
  /**
   * 关闭页面 loading
   */
  hideLoading,
  /**
   * 封装 navigateTo
   */
  navigateTo,
  /**
   * 封装一个带有时效性的缓存方法
   */
  setStorageSyncWithTime,
  /**
   * 获取时效性缓存的方法
   */
  getStorageSyncWithTime,
  /**
   * 判断是否登录
   */
  doLogin,
  /** 
   * 判断是否是支付宝环境
   * 
  */
  isAlipay,
  /** 
   * 判断是否是H5环境
   * 
  */
  isH5,
}

function request({
  url = '',
  params = {}, //请求参数
  method = 'GET',
  ...rest
}: RequestProps): Promise<any> {
  return new Promise((resolve, reject) => {
    Taro.request({
      url,
      data: params,
      method,
      ...rest
    })
      .then((res) => {
        const { data } = res
        // 成功
        if (data?.code === 200) {
          resolve(data)
        } else {
          // 不是预期的结果
          reject(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

function showLoading(param: showLoadingProps = ""): Promise<any> {
  let dptOptions: loadingDptOptions = {
    title: '加载中...',
    mask: true // 防止触摸穿透
  }

  dptOptions = judgeType(dptOptions, param)

  return Taro.showLoading(dptOptions)
}

function showToast(param: showLoadingProps) {
  let dptOptions: toastDptOptions = {
    title: '温馨提示', // 提示内容
    icon: 'none',
    mask: true,
    duration: 2000, // 提示时间
  }

  dptOptions = judgeType(dptOptions, param)

  return Taro.showToast(dptOptions)
}

function hideLoading() {
  Taro.hideLoading()
}

/**
 * 
 * @param url '页面路径'
 * @param data '页面参数'
 */
function navigateTo({ url, data = '' }) {
  const searchStr = objToString(data)

  return Taro.navigateTo({
    url: `${url}?${searchStr}`
  })
}

/**
 * 
 * @param key 缓存的配置
 * @param value 缓存的 value 值
 * @param time 缓存的时间
 */
function setStorageSyncWithTime(key, value, time) {
  try {
    const curTime = Date.now()
    const expireTime = curTime + time * 1000
    setStorageSync(key, {
      [key]: value,
      expireTime
    })
  } catch (error) {
    console.log(error)
  }
}

function getStorageSyncWithTime(key) {
  try {
    const result = getStorageSync(key)
    const { expireTime } = result
    if (Date.now() > expireTime) {
      // 证明缓存过期，则删掉
      removeStorageSync(key)
    } else {
      // 没过期则返回
      return result[key]
    }
  } catch (error) {
    console.log(error)
  }
}

function doLogin(fn) {
  const user = tools.getStorageSyncWithTime('userInfo')
  // 如果用户没登录，就跳到登录页面去
  if (!user?.userPhone) {
    tools.navigateTo({
      url: '/pages/login/login'
    })
  } else {
    fn?.()
  }
}

function isAlipay() {
  return Taro.ENV_TYPE.ALIPAY === Taro.getEnv()
}

function isH5() {
  return Taro.ENV_TYPE.WEB === Taro.getEnv()
}

export default tools
